﻿Imports System.Globalization

Public Class frmOrdenPago

    Dim controller As New ControllerSigeco.controller_compras
    Dim controllerStock As New ControllerSigeco.controller_stock

    Private Sub btnCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelar.Click
        Me.Close()
    End Sub

    Private _codProveedor As Integer = 0

    Public Property codProveedor() As Integer
        Get
            Return _codProveedor
        End Get
        Set(ByVal value As Integer)
            _codProveedor = value
        End Set
    End Property

    Private _codOrdenPago As Integer = 0
    Public Property codOrdenPago() As Integer
        Get
            Return _codOrdenPago
        End Get
        Set(ByVal value As Integer)
            _codOrdenPago = value
        End Set
    End Property

    Private _codCompra As Integer = 0

    Public Property codCompra() As Integer
        Get
            Return _codCompra
        End Get
        Set(ByVal value As Integer)
            _codCompra = value
        End Set
    End Property

    Private m_frmBusMercaderia As frmMercaderiaBuscador
    Public Property frmBusMercaderia() As frmMercaderiaBuscador
        Get
            Return m_frmBusMercaderia
        End Get
        Set(ByVal value As frmMercaderiaBuscador)
            m_frmBusMercaderia = value
        End Set
    End Property

    Private m_frmBusProveedor As frmProveedorBuscador
    Public Property frmBusProveedor() As frmProveedorBuscador
        Get
            Return m_frmBusProveedor
        End Get
        Set(ByVal value As frmProveedorBuscador)
            m_frmBusProveedor = value
        End Set
    End Property

    Private m_frmBusFactura As frmFacturaBuscador
    Public Property frmBusFactura() As frmFacturaBuscador
        Get
            Return m_frmBusFactura
        End Get
        Set(ByVal value As frmFacturaBuscador)
            m_frmBusFactura = value
        End Set
    End Property

    Private Sub btnBuscProveedor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBuscProveedor.Click

        frmBusProveedor = New frmProveedorBuscador
        frmBusProveedor.ShowDialog()
        txtProveedor.Text = frmBusProveedor.ProveedorDesc
        codProveedor = frmBusProveedor.codProveedor
        If codProveedor > 0 Then
            btnBuscMercaderia.Focus()
        End If

    End Sub

    Private Sub btnBuscMercaderia_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBuscMercaderia.Click

        frmBusFactura = New frmFacturaBuscador
        frmBusFactura.codCliente = codProveedor
        frmBusFactura.conSaldo = True
        frmBusFactura.esCompra = True
        frmBusFactura.esOP = True
        frmBusFactura.ShowDialog()
        codCompra = frmBusFactura.codCompra

        If codCompra > 0 Then
            Dim dt As New DataTable
            dt = controller.get_Compras_ByID(oiml.dbConn, codCompra)
            If Not dt Is Nothing Then
                codCompra = dt.Rows(0)("idCompra")
                txtFactura.Text = "NRO: " & dt.Rows(0)("nroComprobante") & _
                " - FECHA: " & dt.Rows(0)("fecha_") & _
                " - VTO: " & dt.Rows(0)("fechaVencimiento_")
                txtSaldo.Text = Decimal.Parse(dt.Rows(0)("totalFacturaSaldo").ToString).ToString("N0")
            Else
                MessageBox.Show("No se registran deudas con la factura ingresada. Favor verifique la cuenta del proveedor.", "Informe", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If

            txtMontoCobro.Focus()

        End If

    End Sub

    Private Sub txtcantidad_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtMontoCobro.Leave
        If Not IsNumeric(txtMontoCobro.Text) Then
            txtMontoCobro.Text = 0
        End If
    End Sub

    Private Sub frmVentas_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        dgvdetalle.AutoGenerateColumns = False
        btnImprimir.Visible = False

        oiml.CargarCombos(cboBanco, "banco", "idbanco", controller.get_Bancos_All(oiml.dbConn))

        cboFormaPago.SelectedIndex = 0
        cboEstado.SelectedIndex = 0

        CargarOrdenPago()
        ControlFormaPago()

    End Sub

    Private Sub CargarOrdenPagoDetalle()
        Try

            codCompra = 0
            txtFactura.Text = ""
            txtSaldo.Text = 0
            txtMontoCobro.Text = 0
            txtObs.Text = ""
            txtTitular.Text = ""
            txtNroCheque.Text = ""

            Dim ds As New DataTable
            ds = controller.get_OrdenPago_Detalles_All(oiml.dbConn, codOrdenPago)

            If Not ds Is Nothing Then
                dgvdetalle.DataSource = ds
            Else
                dgvdetalle.DataSource = Nothing
            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    Dim ci As CultureInfo

    Private Sub CargarOrdenPago()
        Try
            If codOrdenPago > 0 Then

                Dim ds As New DataTable
                ds = controller.get_OrdenPago_ByID(oiml.dbConn, codOrdenPago)

                If Not ds Is Nothing Then

                    txtActualizadoFecha.Text = ds.Rows(0)("actualizadoFecha_")
                    txtActualizadoPor.Text = ds.Rows(0)("usuario")

                    'ci = Thread.CurrentThread.CurrentCulture

                    txtProveedor.Text = ds.Rows(0)("proveedor")
                    codProveedor = ds.Rows(0)("idProveedor")
                    txtTotalOrden.Text = Decimal.Parse(ds.Rows(0)("montoTotal").ToString).ToString("N0")
                    'ds.Rows(0)("totalFacturaSaldo").ToString("D")

                    'ds.Rows(0)("totalFactura").ToString("D")

                    'ds.Rows(0)("totalFacturaIVA").ToString("D")
                    nroFactura.Text = ds.Rows(0)("nroOrden")
                    fechaFactura.Value = ds.Rows(0)("fecha")

                    txtConcepto.Text = ds.Rows(0)("concepto")
                    cboEstado.Text = ds.Rows(0)("estado")

                    ControlEstados()


                    'btnGrabar.Enabled = True
                    'btnEliminar.Enabled = True

                    CargarOrdenPagoDetalle()

                End If

            Else
                cboEstado.Text = "EN PROCESO"
                nroFactura.Focus()

            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    Private Sub ControlEstados()

        If cboEstado.Text = "APROBADO" Then

            nroFactura.Enabled = False
            fechaFactura.Enabled = False
            cboFormaPago.Enabled = False
            'fechaVto.Enabled = False
            'cboTipo.Enabled = False

            txtConcepto.Enabled = False
            txtFactura.Enabled = False
            txtMontoCobro.Enabled = False

            btnBuscMercaderia.Enabled = False
            btnBuscProveedor.Enabled = False
            'btnBuscOrdenCompra.Enabled = False

            btnGrabar.Enabled = False
            btnAgregarDetalle.Enabled = False

            btnConfirmar.Visible = False

            btnEliminar.Enabled = False
            btnEliminarDetalle.Enabled = False
            'cboVendedor.Enabled = False

            'txtcantidad.Enabled = False
            'txtprecio.Enabled = False
            'cboIVA.Enabled = False

            btnCancelar.Focus()

        ElseIf cboEstado.Text = "ANULADO" Then

            nroFactura.Enabled = False
            fechaFactura.Enabled = False
            cboFormaPago.Enabled = False
            'fechaVto.Enabled = False
            'cboTipo.Enabled = False

            txtConcepto.Enabled = False
            txtFactura.Enabled = False
            txtMontoCobro.Enabled = False

            btnBuscMercaderia.Enabled = False
            btnBuscProveedor.Enabled = False
            'btnBuscOrdenCompra.Enabled = False

            btnGrabar.Enabled = False
            btnAgregarDetalle.Enabled = False
            btnEliminarDetalle.Enabled = False
            btnConfirmar.Enabled = False
            btnEliminar.Enabled = False
            btnAnular.Enabled = False

            'cboVendedor.Enabled = False

            'txtcantidad.Enabled = False
            'txtprecio.Enabled = False
            'cboIVA.Enabled = False

            btnCancelar.Focus()

        Else
            btnConfirmar.Enabled = True
        End If

    End Sub

    Private Function ValidarCampos() As Boolean

        Dim controlCampos As Boolean = False

        If nroFactura.Text = "" Then
            ErrorProvider1.SetError(nroFactura, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(nroFactura, "")
        End If        '

        If txtProveedor.Text = "" Then
            ErrorProvider1.SetError(txtProveedor, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtProveedor, "")
        End If        '

        If txtConcepto.Text = "" Then
            ErrorProvider1.SetError(txtConcepto, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtConcepto, "")
        End If        '

        Return controlCampos

    End Function

    Private Function ValidarCamposDetalle() As Boolean

        Dim controlCampos As Boolean = False

        If txtFactura.Text = "" Then
            ErrorProvider1.SetError(txtFactura, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtFactura, "")
        End If        '

        If txtMontoCobro.Text = "" Or Not IsNumeric(txtMontoCobro.Text) Then
            ErrorProvider1.SetError(txtMontoCobro, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtMontoCobro, "")
        End If        '

        'If txtprecio.Text = "" Or Not IsNumeric(txtprecio.Text) Then
        '    ErrorProvider1.SetError(txtprecio, "Campo obligatorio")
        '    controlCampos = True
        'Else
        '    ErrorProvider1.SetError(txtprecio, "")
        'End If        '

        Return controlCampos

    End Function

    Private Sub btnEliminar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEliminar.Click
        If codOrdenPago > 0 Then

            If MessageBox.Show("Desea eliminar el registro seleccionado?", "Orden de Pago", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                If controller.Delete_OrdenPago(oiml.dbConn, codOrdenPago, oiml.idUsuario) Then
                    Me.Close()

                Else
                    MessageBox.Show("Error: " & controller.MessageError.Message, "Orden de Pago", MessageBoxButtons.OK, MessageBoxIcon.Error)

                End If

            End If

        End If

    End Sub

    Private Sub btnGrabar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGrabar.Click

        If ValidarCampos() Then
            Exit Sub
        End If

        If codOrdenPago = 0 Then
            codOrdenPago = controller.Insert_OrdenPago(oiml.dbConn, nroFactura.Text, fechaFactura.Value, _
                                                  codProveedor, txtConcepto.Text, _
                                                  cboEstado.Text, oiml.idUsuario)

            If codOrdenPago > 0 Then
                CargarOrdenPago()
                MessageBox.Show("Registro grabado con exito!", "Orden de Pago", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Orden de Pago", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        Else
            If controller.Update_OrdenPago(oiml.dbConn, codOrdenPago, nroFactura.Text, fechaFactura.Value, _
                                                  codProveedor, txtConcepto.Text, _
                                                  cboEstado.Text, oiml.idUsuario) Then
                CargarOrdenPago()
                MessageBox.Show("Registro grabado con exito!", "Orden de Pago", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)


            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Orden de Pago", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        End If

    End Sub

    Private Sub dgvdetalle_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgvdetalle.KeyDown
        If e.KeyCode = Keys.Enter Then
            If dgvdetalle.SelectedRows.Count > 0 Then

                codCompra = dgvdetalle.SelectedRows(0).Cells(0).Value

            End If
        End If
    End Sub

    Private Sub dgvdetalle_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgvdetalle.DoubleClick
        If dgvdetalle.SelectedRows.Count > 0 Then

            codCompra = dgvdetalle.SelectedRows(0).Cells(0).Value

        End If
    End Sub

    Private Sub dgvdetalle_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvdetalle.CellClick
        Try

            If dgvdetalle.SelectedRows.Count > 0 Then

                codCompra = dgvdetalle.SelectedRows(0).Cells(0).Value

            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub btnEliminarDetalle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEliminarDetalle.Click

        If codCompra > 0 Then

            If MessageBox.Show("Desea eliminar el registro seleccionado?", "Orden de Pago", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                If controller.Delete_OrdenPago_Detalle(oiml.dbConn, codCompra, oiml.idUsuario, codOrdenPago) Then
                    CargarOrdenPago()

                Else
                    MessageBox.Show("Error: " & controller.MessageError.Message, "Orden de Pago", MessageBoxButtons.OK, MessageBoxIcon.Error)

                End If

            End If

        End If

    End Sub

    Private Sub btnAgregarDetalle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgregarDetalle.Click

        If ValidarCampos() Then
            Exit Sub
        End If

        If ValidarCamposDetalle() Then
            Exit Sub
        End If

        Dim idBanco As Integer = 0
        If cboBanco.Visible Then
            idBanco = cboBanco.SelectedValue
        End If

        Dim fechaParamDiferido As String = ""
        If fechaDiferido.Visible Then
            fechaParamDiferido = fechaDiferido.Value.ToShortDateString
        End If

        If codOrdenPago = 0 Then
            codOrdenPago = controller.Insert_OrdenPago(oiml.dbConn, nroFactura.Text, fechaFactura.Value, _
                                                  codProveedor, txtConcepto.Text, _
                                                  cboEstado.Text, oiml.idUsuario)
        Else
            If controller.Update_OrdenPago(oiml.dbConn, codOrdenPago, nroFactura.Text, fechaFactura.Value, _
                                                  codProveedor, txtConcepto.Text, _
                                                  cboEstado.Text, oiml.idUsuario) Then
            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Orden de Pago", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        End If

        If codOrdenPago > 0 And codCompra > 0 Then

            If controller.Insert_OrdenPago_Detalle(oiml.dbConn, codOrdenPago, codCompra, txtMontoCobro.Text, txtObs.Text, _
                                                   cboFormaPago.Text, oiml.idUsuario, oiml.idMovimientoCajaActual, True, _
                                                   idBanco, txtNroCheque.Text, txtTitular.Text, fechaParamDiferido) Then
                CargarOrdenPago()
                MessageBox.Show("Registro grabado con exito!", "Orden de Pago", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Orden de Pago", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If

        End If

    End Sub

    Private Sub btnConfirmar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConfirmar.Click

        If ValidarCampos() Then
            Exit Sub
        End If

        If codOrdenPago > 0 Then

            nroFactura.Text = controller.get_OrdenPago_Documento(oiml.dbConn, "OP", oiml.idUsuario)

            If controller.Update_OrdenPago_Estado(oiml.dbConn, codOrdenPago, "APROBADO", oiml.idUsuario, nroFactura.Text) Then
                CargarOrdenPago()
                MessageBox.Show("Registro confirmado con exito!", "Orden de Pago", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Orden de Pago", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If

        End If

    End Sub

    Private Sub btnAnular_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAnular.Click
        If codOrdenPago > 0 Then
            If MessageBox.Show("Desea anular el registro seleccionado?", "Orden de Pago", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                If controller.Update_OrdenPago_Estado(oiml.dbConn, codOrdenPago, "ANULADO", oiml.idUsuario, nroFactura.Text) Then
                    Me.Close()

                Else
                    MessageBox.Show("Error: " & controller.MessageError.Message, "Orden de Pago", MessageBoxButtons.OK, MessageBoxIcon.Error)

                End If

            End If
        End If
    End Sub

    Private Sub txtFactura_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        If e.KeyCode = Keys.Enter Then
            btnBuscMercaderia_Click(sender, e)
        End If
    End Sub


    'codigo para textbox numerico--------------inicio-------------------
    Private Sub txtprecio_changed(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtMontoCobro.TextChanged
        If IsNumeric(txtMontoCobro.Text) Then

            If txtMontoCobro.Text = "" Then
                txtMontoCobro.Text = Nothing
                textWithcomma = "0"
                'this property maintain the content of textbox with comma
                'this property maintain the content of textbox without comma
                textWithoutcomma = "0"
            Else
                If txtMontoCobro.Text <> "" Then
                    Dim d As Double = Convert.ToDouble(skipComma(txtMontoCobro.Text))
                    txtMontoCobro.Text = d.ToString("N0") 'd.ToString("#.#", System.Globalization.CultureInfo.InvariantCulture)
                    textWithcomma = txtMontoCobro.Text
                    'property maintain content of textbox with comma
                    'property maintain content of textbox without comma
                    textWithoutcomma = skipComma(txtMontoCobro.Text)
                End If
            End If

            txtMontoCobro.[Select](txtMontoCobro.Text.Length, 0)

        End If
    End Sub

    Public textWithcomma As String
    Public textWithoutcomma As String

    Public Function skipComma(ByVal str As String) As String
        Dim ss As String() = Nothing
        Dim strnew As String = ""
        If str = "" Then
            strnew = "0"
        Else
            ss = str.Split("."c)
            For i As Integer = 0 To ss.Length - 1
                strnew += ss(i)
            Next
        End If
        Return strnew
    End Function

    Private Sub txtprecio_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtMontoCobro.KeyPress
        If Not Char.IsControl(e.KeyChar) AndAlso Not Char.IsDigit(e.KeyChar) AndAlso (e.KeyChar <> "."c) Then
            e.Handled = True
        End If

        ' only allow one decimal point
        If (e.KeyChar = "."c) AndAlso (TryCast(sender, TextBox).Text.IndexOf("."c) > -1) Then
            e.Handled = True
        End If

    End Sub
    'codigo para textbox numerico--------------inicio-------------------


    Private Sub cboFormaPago_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboFormaPago.SelectedIndexChanged
        ControlFormaPago()

    End Sub

    Private Sub ControlFormaPago()
        If Not cboFormaPago.Text.Contains("CHEQUE") Then
            txtTitular.Text = ""

            lblTitular.Visible = False
            txtTitular.Visible = False
            txtNroCheque.Visible = False

            txtNroCheque.Text = ""


            lblCheque.Visible = False
            lblFechaDiferido.Visible = False
            fechaDiferido.Visible = False

            cboBanco.Visible = False
            lblBanco.Visible = False
        ElseIf cboFormaPago.Text.Contains("CHEQUE") Then
            txtTitular.Text = ""
            lblTitular.Visible = True

            txtTitular.Visible = True
            txtNroCheque.Visible = True

            txtNroCheque.Text = ""
            lblCheque.Visible = True

            If cboFormaPago.Text.Contains("DIFERIDO") Then
                fechaDiferido.Visible = True
                lblFechaDiferido.Visible = True
            End If

            cboBanco.Visible = True
            lblBanco.Visible = True
        End If
    End Sub


End Class